import Vue from 'vue'
import Router from 'vue-router'
import Login from './views/Login.vue'
import Register from './views/Register.vue'
import Home from './views/Home.vue'
import AdminHomeProduct from './views/AdminHomeProduct.vue'
import AdminHomeOrder from './views/AdminHomeOrder.vue'
import AdminHomeUser from './views/AdminHomeUser.vue'
import Cart from './views/Cart.vue'
import ProductDetail from './views/ProductDetail.vue'
import Order from './views/Order.vue'
import BrowseLog from './views/AdminHomeUserBrowseLog.vue'
import OrderLog from './views/AdminHomeUserOrderLog.vue'

Vue.use(Router)

const router = new Router({
  mode: 'history', // 使用 history 模式，URL 中不会有 #
  routes: [
    {
      path: '/',
      redirect: '/login', // 当访问根路径时，重定向到 /login
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
    },
    {
      path: '/home',
      name: 'UserHome',
      component: Home,
      meta: { requiresAuth: true, role: 'CUSTOMER' },
    },
    {
      path: '/home/:id',
      name: 'ProductDetail',
      component: ProductDetail,
      meta: { requiresAuth: true, role: 'CUSTOMER' },
    },
    {
      path: '/cart',
      name: 'ProductCart',
      component: Cart,
      meta: { requiresAuth: true, role: 'CUSTOMER' },
    },
    {
      path: '/order',
      name: 'OrderHistory',
      component: Order,
      meta: { requiresAuth: true, role: 'CUSTOMER' },
    },
    {
      path: '/adminhomeproduct',
      name: 'AdminHomeProduct',
      component: AdminHomeProduct,
      meta: { requiresAuth: true, role: 'ADMIN' },
    },
    {
      path: '/adminhomeorder',
      name: 'AdminHomeOrder',
      component: AdminHomeOrder,
      meta: { requiresAuth: true, role: 'ADMIN' },
    },
    {
      path: '/adminhomeuser',
      name: 'AdminHomeUser',
      component: AdminHomeUser,
      meta: { requiresAuth: true, role: 'ADMIN' },
    },
    {
      path: '/adminhomeuser/browse/:id',
      name: 'BrowseLog',
      component: BrowseLog,
      meta: { requiresAuth: true, role: 'ADMIN' },
    },
    {
      path: '/adminhomeuser/order/:id',
      name: 'OrderLog',
      component: OrderLog,
      meta: { requiresAuth: true, role: 'ADMIN' },
    },
  ],
})
// 添加导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('jwtToken')

  // 检查是否需要授权
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!token) {
      // 如果没有 token，重定向到登录页面
      next({ path: '/login' })
    } else {
      // 解析 JWT 获取角色
      const payload = JSON.parse(atob(token.split('.')[1])) // 解码 JWT
      const userRole = payload.role

      // 检查角色是否匹配
      if (to.meta.role && userRole !== to.meta.role) {
        // 如果角色不匹配，重定向到登录或其他页面
        next({ path: '/login' })
      } else {
        next() // 角色匹配，继续
      }
    }
  } else {
    next() // 不需要授权，继续
  }
})
export default router
